<template>
  <div class="chat-container">
    <!-- 聊天消息区域 -->
    <div class="message-container" ref="messageContainer">
      <div v-for="(msg, index) in messages" :key="index" 
           :class="['message', msg.type === 'user' ? 'message-user' : 'message-assistant']">
        <div class="avatar">
          <img :src="msg.type === 'user' ? userAvatar : assistantAvatar" />
        </div>
        <div class="content">
          <div class="name">{{ msg.type === 'user' ? '你' : 'AI助手' }}</div>
          <!-- 根据消息类型显示不同的内容 -->
          <div v-if="!msg.isJson" class="text">{{ msg.content }}</div>
          <div v-else class="json-container">
            <!-- JSON数据默认以列表形式展示 -->
            <div class="json-list">
              <template v-if="msg.data.type === 'pie'">
                <div v-for="(item, i) in msg.data.data" :key="i" class="json-item">
                  <span class="item-name">{{ item.name }}</span>
                  <span class="item-value">{{ item.value }}</span>
                  <div class="item-bar" :style="{ width: (item.value / getMaxValue(msg.data.data)) * 100 + '%' }"></div>
                </div>
              </template>
              <template v-else>
                <div v-for="(value, i) in msg.data.series" :key="i" class="json-item">
                  <span class="item-name">{{ msg.data.xAxis[i] }}</span>
                  <span class="item-value">{{ value }}</span>
                  <div class="item-bar" :style="{ width: (value / Math.max(...msg.data.series)) * 100 + '%' }"></div>
                </div>
              </template>
            </div>
            <!-- 切换图表按钮 -->
            <div class="chart-actions">
              <el-button 
                size="small" 
                type="primary" 
                @click="toggleChart(index)"
                :class="{ active: msg.showChart }"
              >
                <i :class="msg.showChart ? 'el-icon-document' : 'el-icon-data-analysis'" />
                {{ msg.showChart ? '显示数据' : '显示图表' }}
              </el-button>
            </div>
            <!-- 图表区域 -->
            <div v-if="msg.showChart" class="chart-container">
              <div :class="'chart'" :style="{height:'350px',width:'100%'}" :id="'chart-' + index" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-container">
      <div class="input-wrapper">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="输入消息或按住麦克风说话..."
          @keyup.enter.native="sendMessage"
          resize="none"
        />
        <div class="button-group">
          <el-tooltip content="按住说话" placement="top">
            <el-button 
              class="mic-button"
              :class="{ recording: isRecording }"
              @mousedown="startRecording"
              @mouseup="stopRecording"
              icon="el-icon-microphone"
            />
          </el-tooltip>
          <el-button type="primary" @click="sendMessage" :disabled="!inputMessage.trim()">
            <i class="el-icon-s-promotion" />
            发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons')
import resize from '@/views/dashboard/mixins/resize'

export default {
  name: "ChatIndex",
  mixins: [resize],
  data() {
    return {
      messages: [],
      inputMessage: "",
      isRecording: false,
      mediaRecorder: null,
      audioChunks: [],
      userAvatar: require("@/assets/images/profile.jpg"),
      assistantAvatar: require("@/assets/images/ai-avatar.png"),
      charts: {}
    };
  },
  methods: {
    sendMessage() {
      if (!this.inputMessage.trim()) return;
      
      this.messages.push({
        type: 'user',
        content: this.inputMessage
      });

      setTimeout(() => {
        const mockData = this.getMockData();
        this.handleResponse(mockData);
      }, 1000);

      this.inputMessage = "";
    },

    handleResponse(data) {
      let messageContent = '';
      let isJson = false;
      let chartOptions = null;
      let jsonData = null;

      if (typeof data === 'string') {
        messageContent = data;
      } else if (this.isChartData(data)) {
        isJson = true;
        jsonData = data;
        chartOptions = this.generateChartOptions(data, data.type);
        messageContent = '数据已就绪，可以切换图表/列表视图：';
      }

      const message = {
        type: 'assistant',
        content: messageContent,
        isJson,
        data: jsonData,
        chartOptions,
        showChart: false // 默认不显示图表
      };

      this.messages.push(message);
      this.scrollToBottom();
    },

    isChartData(data) {
      return data && typeof data === 'object' && (data.xAxis || data.series || data.data);
    },

    getChartType(data) {
      if (data.type) return data.type;
      if (data.series && data.series[0] && data.series[0].type) return data.series[0].type;
      if (data.data && data.data.length > 0) return 'pie';
      return 'bar';
    },

    generateChartOptions(data, type) {
      const baseOptions = {
        tooltip: {
          trigger: type === 'pie' ? 'item' : 'axis',
          axisPointer: {
            type: 'cross'
          },
          padding: [5, 10]
        },
        grid: {
          left: 10,
          right: 10,
          bottom: 20,
          top: 30,
          containLabel: true
        },
        legend: {
          data: type === 'pie' ? null : ['数据']
        }
      };

      const typeOptions = {
        pie: {
          series: [{
            name: '访问来源',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: data.data || [],
            animationDuration: 2800,
            animationEasing: 'cubicInOut'
          }]
        },
        bar: {
          xAxis: {
            type: 'category',
            boundaryGap: true,
            data: data.xAxis || [],
            axisTick: {
              show: false
            }
          },
          yAxis: {
            type: 'value',
            axisTick: {
              show: false
            }
          },
          series: [{
            name: '数据',
            type: 'bar',
            data: data.series || [],
            animationDuration: 2800,
            animationEasing: 'cubicInOut'
          }]
        },
        line: {
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: data.xAxis || [],
            axisTick: {
              show: false
            }
          },
          yAxis: {
            type: 'value',
            axisTick: {
              show: false
            }
          },
          series: [{
            name: '数据',
            type: 'line',
            smooth: true,
            data: data.series || [],
            animationDuration: 2800,
            animationEasing: 'cubicInOut',
            itemStyle: {
              normal: {
                color: '#3888fa',
                lineStyle: {
                  color: '#3888fa',
                  width: 2
                },
                areaStyle: {
                  color: '#f3f8ff'
                }
              }
            }
          }]
        }
      };

      return { ...baseOptions, ...typeOptions[type] };
    },

    initChart(index, options) {
      this.$nextTick(() => {
        const chartDom = document.getElementById(`chart-${index}`);
        if (!chartDom) return;
        
        if (this.charts[index]) {
          this.charts[index].dispose();
        }
        
        try {
          const chart = echarts.init(chartDom, 'macarons');
          chart.setOption(options);
          this.charts[index] = chart;
        } catch (error) {
          console.error('初始化图表失败:', error);
        }
      });
    },

    getMockData() {
      const types = ['text', 'pie', 'bar', 'line'];
      const type = types[Math.floor(Math.random() * types.length)];

      const mockDataMap = {
        pie: {
          type: 'pie',
          data: [
            { value: 335, name: '直接访问' },
            { value: 310, name: '邮件营销' },
            { value: 234, name: '联盟广告' },
            { value: 135, name: '视频广告' },
            { value: 1548, name: '搜索引擎' }
          ]
        },
        bar: {
          type: 'bar',
          xAxis: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
          series: [120, 200, 150, 80, 70, 110, 130]
        },
        line: {
          type: 'line',
          xAxis: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
          series: [820, 932, 901, 934, 1290, 1330, 1320]
        },
        text: '这是一个普通的文本回复'
      };

      return mockDataMap[type];
    },

    async startRecording() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        this.mediaRecorder = new MediaRecorder(stream);
        this.audioChunks = [];
        this.isRecording = true;

        this.mediaRecorder.ondataavailable = (event) => {
          this.audioChunks.push(event.data);
        };

        this.mediaRecorder.start();
      } catch (err) {
        this.$message.error('无法访问麦克风');
        console.error('录音错误:', err);
      }
    },

    async stopRecording() {
      if (!this.mediaRecorder) return;
      
      this.mediaRecorder.stop();
      this.isRecording = false;

      this.mediaRecorder.onstop = async () => {
        const audioBlob = new Blob(this.audioChunks);
        console.log('录音完成，音频大小:', audioBlob.size);
      };
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messageContainer;
        container.scrollTop = container.scrollHeight;
      });
    },

    // 添加切换图表/列表显示的方法
    toggleChart(index) {
      const message = this.messages[index];
      if (!message.isJson) return;

      message.showChart = !message.showChart;
      this.$set(this.messages, index, message);

      if (message.showChart) {
        this.$nextTick(() => {
          this.initChart(index, message.chartOptions);
        });
      }
    },

    // 添加获取最大值的方法
    getMaxValue(data) {
      return Math.max(...data.map(item => item.value));
    }
  },
  
  beforeDestroy() {
    Object.keys(this.charts).forEach(key => {
      if (this.charts[key]) {
        this.charts[key].dispose();
        delete this.charts[key];
      }
    });
  }
};
</script>

<style scoped lang="scss">
.chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f7f7f7;
  padding: 20px;
}

.message-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  margin-bottom: 20px;
  
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.2);
    border-radius: 3px;
  }
}

.message {
  display: flex;
  margin-bottom: 30px;
  opacity: 0;
  animation: fadeIn 0.3s ease forwards;
  
  .avatar {
    width: 40px;
    height: 40px;
    margin-right: 16px;
    flex-shrink: 0;
    
    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      object-fit: cover;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      border: 2px solid white;
    }
  }

  .content {
    flex: 1;
    max-width: calc(100% - 56px);
    
    .name {
      font-size: 13px;
      color: #999;
      margin-bottom: 6px;
    }

    .text {
      padding: 12px 16px;
      border-radius: 12px;
      max-width: 80%;
      word-break: break-word;
      line-height: 1.5;
      position: relative;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }
}

.message-user {
  flex-direction: row-reverse;
  
  .avatar {
    margin-right: 0;
    margin-left: 16px;
  }

  .content {
    align-items: flex-end;
    
    .text {
      background: #007AFF;
      color: white;
      margin-left: auto;
    }
  }
}

.message-assistant {
  .content .text {
    background: white;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  }
}

.json-container {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin: 8px 0;
  max-width: 800px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

  .json-list {
    margin-bottom: 16px;

    .json-item {
      position: relative;
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .item-name {
        width: 120px;
        color: #666;
        font-size: 14px;
        z-index: 1;
      }

      .item-value {
        width: 80px;
        font-weight: 500;
        color: #333;
        margin-left: auto;
        text-align: right;
        z-index: 1;
      }

      .item-bar {
        position: absolute;
        left: 0;
        top: 0;
        height: 100%;
        background: rgba(24, 144, 255, 0.1);
        transition: width 0.3s ease;
      }
    }
  }

  .chart-actions {
    display: flex;
    justify-content: flex-end;
    margin: 8px 0;

    .el-button {
      transition: all 0.3s ease;
      
      &.active {
        background: #1890ff;
        color: white;
      }
    }
  }
}

.chart-container {
  margin-top: 16px;
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.input-container {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);

  .input-wrapper {
    position: relative;

    .el-textarea {
      textarea {
        border-radius: 8px;
        padding: 12px;
        font-size: 14px;
        line-height: 1.6;
        resize: none;
        
        &:focus {
          box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
        }
      }
    }
  }

  .button-group {
    display: flex;
    justify-content: flex-end;
    margin-top: 12px;
    gap: 12px;
  }
}

.mic-button {
  &.recording {
    color: #f56c6c;
    animation: pulse 1s infinite;
  }
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
